<template>
  <el-dialog
    v-model="visible"
    :title="'修改项目'"
    width="30%"
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="项目名称">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 项目修改对话框组件
 * 功能：
 * - 提供修改项目的表单界面
 * - 表单字段验证
 * - 提交修改数据到后端
 * - 处理操作结果反
 * - 与父组件通过事件通信
 */
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updateProjectInfo } from '@/api/project'
import { mockUpdateProject } from '@/api/mock/projectMock'

const props = defineProps({
  openKey: String,
  projectData: Object
})

const emit = defineEmits(['setMData'])

const visible = ref(false)
// 表单数据
const form = reactive({
  id: '',  // 项目ID
  name: '' // 项目名称
})

/**
 * 打开修改对话框
 * @param {Object} project - 要修改的项目数据
 */
const handleOpen = (project) => {
  form.id = project.id
  form.name = project.name
  visible.value = true
}

/**
 * 关闭对话框
 */
const handleClose = () => {
  visible.value = false
}

/**
 * 提交表单修改
 * 处理修改逻辑，区分开发/生产环境
 */
const handleSubmit = async () => {
  try {
    if (import.meta.env.DEV) {
      const res = await mockUpdateProject(form)
      if (res.data) {
        ElMessage.success('修改成功')
        emit('setMData', 'refreshList', true)
      }
    } else {
      await updateProjectInfo(form)
      ElMessage.success('修改成功')
      emit('setMData', 'refreshList', true)
    }
    handleClose()
  } catch (error) {
    ElMessage.error(`修改失败: ${error.message}`)
  }
}

defineExpose({
  handleOpen
})
</script>
